function bvalue = hasfields(teststruct, varargin)
% hasfields  - test whether a struct has the same fields as a template
%
% FORMAT:       boolval = hasfields(teststruct, template [, onlythese])
%
% Input fields:
%
%       teststruct  struct array that is tested
%       template    template struct that will be used
%       onlythese   optional argument, if given only returns true if no
%                   other fields are presents in teststruct
%
% Note: the order of the fieldnames is irrelevant for the test!
%
% See also ISFIELD.

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
   ~isstruct(teststruct) || ...
   ~isstruct(varargin{1})
    error( ...
        'BVQXtools:BadArgument', ...
        'Too few or bad input arguments given.' ...
    );
end
template = varargin{1};

% init return value
bvalue = false;

% get fieldnames
does = fieldnames(teststruct);
must = fieldnames(template);

% return false if number of fields mismatch
if nargin > 2 && ...
    numel(does) ~= numel(must)
    return;
end

% test every must-fields
for fc = 1:length(must)
    if ~any(strcmp(does,must{fc}))
        return;
    end
end

% all checks passed
bvalue = true;
